package com.example.aigc_education.integration.processor.v1;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.aigc_education.common.BusinessException;
import com.example.aigc_education.integration.config.RestTemplateUtils;
import com.example.aigc_education.integration.constants.CozeConstant;
import com.example.aigc_education.integration.emuns.CozeAsyncWorkflow;
import com.example.aigc_education.integration.impl.CozeTokenIntegrationImpI;
import com.example.aigc_education.integration.processor.v1.async.CozeAsyncPlanRequest;
import com.example.aigc_education.integration.request.CozeRequest;
import com.example.aigc_education.integration.response.CozeAsyncResponse;
import com.example.aigc_education.integration.response.CozeResponse;
import com.example.aigc_education.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Slf4j
public abstract class CozeAsyncWFProcessor<T> {
    @Autowired
    private CozeTokenIntegrationImpI cozeTokenIntegration;

    private static final String COZE_SYNC_WORKFLOW_URL = "/workflow/run";

    public abstract CozeAsyncWorkflow workflowType();

    protected abstract String workflowId();

    // 设置入参T，返回值为CozeRequest<T>
    protected abstract CozeRequest<T> buildRequest(CozeAsyncPlanRequest request);


    protected abstract boolean isParamValid(CozeRequest<T> request);


    private CozeResponse executeWorkFlow(CozeAsyncPlanRequest request) {
        CozeRequest<T> cozeRequest = buildRequest(request);
        if (!isParamValid(cozeRequest)) {
            log.warn("CozeSyncWFProcessor executeWorkFlow error params:{}", JsonUtils.toJson(request));
            throw new BusinessException("参数校验失败");
        }

        // 设置工作流id 与 是否异步
        cozeRequest.setWorkflowId(workflowId());
        cozeRequest.setAsync(true);

        // 请求头设置
        Map<String, String> headerMap = new HashMap<>();

        String cozeToken = cozeTokenIntegration.getCozeToken();
        headerMap.put("Authorization",String.format("Bearer %s",cozeToken));
        headerMap.put("Content-Type", "application/json");

        // 转换为json对象
        JSONObject jsonObject = (JSONObject) JSON.toJSON(cozeRequest);

        String restResult = Optional.ofNullable(RestTemplateUtils.postHttp(CozeConstant.COZE_URL + COZE_SYNC_WORKFLOW_URL, jsonObject, headerMap))
                .orElseThrow(() -> new BusinessException("请求coze失败"));

        // 将返回结果转换为CozeSyncResponse对象
        return JsonUtils.fromJson(restResult, CozeResponse.class);
    }

    public CozeResponse asyncRunWorkFlow(CozeAsyncPlanRequest request) {
        CozeResponse response = executeWorkFlow(request);
        log.info("CozeSyncWFProcessor asyncRunWorkFlow response:{}", JsonUtils.toJson(response));
        return response;
    }

    public CozeAsyncResponse queryTaskStatus(String workflowId, String executeId) {
        Map<String, String> headerMap = new HashMap<>();
        String cozeToken = cozeTokenIntegration.getCozeToken();
        headerMap.put("Authorization",String.format("Bearer %s",cozeToken));
        headerMap.put("Content-Type", "application/json");
        String url = CozeConstant.COZE_URL + "/workflows/" + workflowId + "/run_histories/" + executeId;
        log.info("CozeSyncWFProcessor queryTaskStatus url:{}", url);
        String restResult = Optional.ofNullable(RestTemplateUtils.getHttp(url,null, headerMap))
                .orElseThrow(() -> new BusinessException("请求coze失败"));
        log.info("CozeSyncWFProcessor queryTaskStatus restResult:{}", restResult);
        CozeAsyncResponse response;
        try {
            response = JsonUtils.fromJson(restResult, CozeAsyncResponse.class);
        } catch (Exception e) {
            log.error("CozeSyncWFProcessor queryTaskStatus error", e);
            throw new BusinessException("请求coze失败");
        }
        return response;
    }

}
